"""
FastAPI 主应用
"""

import logging
import traceback
from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError

from app.config import get_settings
from app.routers import auth, positions, interview
from app.redis_client import test_redis_connection

settings = get_settings()

# 配置日志
logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用生命周期管理

    使用异步上下文管理器替代已弃用的 on_event
    """
    # 启动时执行
    print("=" * 50)
    print(f"🚀 {settings.APP_NAME} V{settings.APP_VERSION} 启动中...")
    print("=" * 50)

    # 测试 Redis 连接
    if test_redis_connection():
        print("✅ Redis 连接成功")
    else:
        print("⚠️  Redis 连接失败，缓存功能可能不可用")

    print("📚 API 文档: http://localhost:8000/docs")
    print("=" * 50)

    yield  # 应用运行期间

    # 关闭时执行
    print("👋 应用关闭")


# 创建 FastAPI 应用
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description="AI 驱动的智能面试系统",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan,  # 使用 lifespan 参数
)

# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该设置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(auth.router)
app.include_router(positions.router)
app.include_router(interview.router)


@app.get("/")
async def root():
    """根路径"""
    return {
        "app": settings.APP_NAME,
        "version": settings.APP_VERSION,
        "message": "欢迎使用智面 - AI 驱动的智能面试系统",
        "docs": "/docs",
    }


@app.get("/health")
async def health_check():
    """健康检查"""
    redis_status = "ok" if test_redis_connection() else "error"

    return {"status": "ok", "redis": redis_status, "version": settings.APP_VERSION}


# 全局异常处理
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """422 参数验证错误处理"""
    # 记录详细的验证错误
    logger.error("=" * 80)
    logger.error("422 参数验证错误")
    logger.error(f"Request URL: {request.url}")
    logger.error(f"Request Method: {request.method}")
    logger.error("错误详情:")

    # 详细输出每个验证错误
    for error in exc.errors():
        logger.error(f"  字段: {' -> '.join(str(loc) for loc in error['loc'])}")
        logger.error(f"  错误类型: {error['type']}")
        logger.error(f"  错误信息: {error['msg']}")
        if "ctx" in error:
            logger.error(f"  上下文: {error['ctx']}")

    # 记录请求的 Content-Type
    content_type = request.headers.get("content-type", "")
    logger.error(f"Content-Type: {content_type}")

    # 记录验证错误中的输入值
    logger.error("接收到的输入值:")
    for error in exc.errors():
        if "input" in error:
            logger.error(f"  {error['loc']}: {error['input']}")

    logger.error("=" * 80)

    return JSONResponse(
        status_code=422,
        content={
            "detail": exc.errors(),
            "message": "请求参数验证失败",
        },
    )


@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    """HTTP 异常处理"""
    # 记录 HTTP 异常
    logger.error(f"HTTP {exc.status_code} Error: {exc.detail}")
    logger.error(f"Request URL: {request.url}")
    logger.error(f"Request Method: {request.method}")

    return JSONResponse(
        status_code=exc.status_code,
        content={"detail": exc.detail, "status_code": exc.status_code},
    )


@app.exception_handler(Exception)
async def general_exception_handler(request, exc):
    """通用异常处理"""
    # 记录完整的异常堆栈
    logger.error("=" * 80)
    logger.error(f"未捕获的异常: {type(exc).__name__}")
    logger.error(f"错误信息: {str(exc)}")
    logger.error(f"Request URL: {request.url}")
    logger.error(f"Request Method: {request.method}")
    logger.error("完整堆栈跟踪:")
    logger.error(traceback.format_exc())
    logger.error("=" * 80)

    return JSONResponse(
        status_code=500,
        content={
            "detail": "服务器内部错误",
            "message": str(exc) if settings.DEBUG else "请联系管理员",
        },
    )


if __name__ == "__main__":

    def init_database():
        from sqlalchemy import text
        from app.database import engine, Base
        from app.models import User, Position, InterviewSession, ChatMessage

        """初始化数据库"""
        print("=" * 60)
        print("🚀 智面数据库初始化")
        print("=" * 60)

        try:
            # 启用 pgvector 扩展
            print("⏳ 启用 pgvector 扩展...")
            with engine.connect() as conn:
                conn.execute(text("CREATE EXTENSION IF NOT EXISTS vector;"))
                conn.commit()
            print("✅ pgvector 扩展已启用")

            # 创建所有表
            print("⏳ 创建数据库表...")
            Base.metadata.create_all(bind=engine)
            print("✅ 数据库表创建完成")

            # 显示创建的表
            print("\n📋 创建的表:")
            print("   - users (用户表)")
            print("   - positions (岗位表)")
            print("   - interview_sessions (面试会话表)")
            print("   - chat_messages (聊天记录表)")

            print("\n" + "=" * 60)
            print("✅ 数据库初始化成功！")
            print("=" * 60)

        except Exception as e:
            print(f"\n❌ 错误: {str(e)}")

    import uvicorn

    init_database()
    uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=settings.DEBUG)
